package com.icinfo.cloud.provider.punish.evideinv.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.dto.EvidenceInfo;
import com.icinfo.cloud.provider.common.enums.ApiVisitDataSourceEnum;
import com.icinfo.cloud.provider.common.enums.TerritoryCodeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.api.dto.DeptInfoSyncDto;
import com.icinfo.cloud.provider.punish.api.dto.LawEnforcerDto;
import com.icinfo.cloud.provider.punish.api.dto.ThirdAppLoginRequest;
import com.icinfo.cloud.provider.punish.approval.constant.AuditStatusConstant;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceHandlePersonRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourcePartyInfo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.evideinv.dto.*;
import com.icinfo.cloud.provider.punish.evideinv.enums.EvidenceCertTypeEnum;
import com.icinfo.cloud.provider.punish.evideinv.enums.EvidenceOperateTypeEnum;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.evideinv.vo.EvidenceAppraisalDocInfoVo;
import com.icinfo.cloud.provider.punish.evideinv.vo.EvidenceNewSignVo;
import com.icinfo.cloud.provider.punish.evideinv.vo.EvidencePageNewVo;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteEventSaveDto;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecutePartyInfoMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteHandlePersonRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteMainInfo;
import com.icinfo.cloud.provider.punish.execute.model.ExecutePartyInfo;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReasonMainRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoStatusChangeRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentCatalogChainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainEvidenceVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReasonMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAppraisalYjgzsMapper;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCriminalTransferFileVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 证据库 新对接
 *
 * @author Administrator
 */
@Service
@Slf4j
public class EvidenceInventoryServiceImpl implements EvidenceInventoryService {

    private final String CODE = "code";
    private final String DATA = "data";
    private final String DL = "dataList";
    private final Integer TWO_HUNDRED = 200;
    @Resource
    ICaseMainInfoService caseMainInfoService;
    @Value("${evidence.appKey}")
    private String appKey;
    @Value("${evidence.appSecret}")
    private String appSecret;
    @Value("${evidenceNew.url}")
    private String apiurl;
    @Value("${evidenceNew.exceptTzUrl}")
    private String exceptTzUrl;
    @Value("${evidenceNew.api.evidencePageList}")
    private String evidencePageList;
    @Value("${evidenceNew.api.deleteAllDraft}")
    private String deleteAllDraft;
    @Value("${evidenceNew.api.deleteDraft}")
    private String deleteDraft;
    @Value("${evidenceNew.api.saveEvent}")
    private String saveEvent;
    @Value("${evidenceNew.api.saveCaseSourceEvent}")
    private String saveCaseSourceEvent;
    @Value("${evidenceNew.api.removeCase}")
    private String removeCase;
    @Value("${evidenceNew.api.buttonUrl}")
    private String buttonUrl;
    @Value("${evidenceNew.api.updateCaseNode}")
    private String updateCaseNode;
    @Value("${evidenceNew.api.saveCaseResultInfo}")
    private String saveCaseResultInfo;
    @Value("${evidenceNew.api.saveAppraisalDoc}")
    private String saveAppraisalDoc;
    @Value("${evidenceNew.api.saveCaseProcessDocument}")
    private String saveCaseProcessDocument;
    @Value("${evidenceNew.api.deleteEvidence}")
    private String deleteEvidence;
    @Value("${evidenceNew.api.updateCpInfo}")
    private String updateCpInfo;
    @Value("${evidenceNew.api.syncDeptInfo}")
    private String syncDeptInfo;
    @Value("${evidenceNew.api.updateLawEnforcer}")
    private String updateLawEnforcer;
    @Value("${evidenceNew.api.getEvidenceByCaseId}")
    private String getEvidenceByCaseId;
    @Value("${evidenceNew.api.deleteEvidenceByCaseId}")
    private String deleteEvidenceByCaseId;
    @Value("${evidenceNew.api.getCaseEvidenceInfo}")
    private String getCaseEvidenceInfo;
    @Resource
    private CaseMainEvidenceMapper caseMainEvidenceMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private CaseDocumentAppraisalYjgzsMapper caseDocumentAppraisalYjgzsMapper;
    @Resource
    private CaseMainInfoStatusChangeRecordMapper caseMainInfoStatusChangeRecordMapper;
    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;
    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;
    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;
    @Resource
    private CaseSourceHandlePersonRecordMapper caseSourceHandlePersonRecordMapper;

    @Resource
    private ExecuteHandlePersonRecordMapper executeHandlePersonRecordMapper;

    @Resource
    private ExecutePartyInfoMapper executePartyInfoMapper;

    @Resource
    private SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IExecuteMainInfoService executeMainInfoService;

    public static void main(String[] args) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        System.out.println(DigestUtils.md5DigestAsHex(("c37c14e6a33711ecb6fb0050568f7529".concat("65683b181ac290efc48d47ac9dcb23710959114d").concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        System.out.println(timestamp);
    }

    /**
     * 获得签名
     *
     * @return
     */
    @Override
    public EvidenceNewSignVo getSign() {
        EvidenceNewSignVo vo = new EvidenceNewSignVo();
        String timestamp = getTimestamp();
        String sign = DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8));
        vo.setSign(sign);
        vo.setTimeStamp(timestamp);
        JSONObject baseInfoRequest = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.add(UserUtil.getUserInfo().getUserId().toString());
        baseInfoRequest.put("userIds", userIds);
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        if (baseInfo.isEmpty()) {
            throw new BusinessException("未获取用户执法信息");
        }
        vo.setExecutorId(baseInfo.get(0).getZfCertList().get(0).getZfCertNo());
        return vo;
    }

    private String getTimestamp() {
        return String.valueOf(System.currentTimeMillis());
    }

    @Override
    public PageResponse<EvidencePageNewVo> getEvidencePage(QueryEvidencePageDto pageDto) {
        PageResponse<EvidencePageNewVo> page = new PageResponse<>();
        QueryEvidencePageDto param = new QueryEvidencePageDto();
        param.setPageNum(1);
        param.setPageSize(1000);
        String caseNo = "";
        String territoryCode = "";
        if (Constant.STRING_1.equals(pageDto.getBusinessType())) {
            CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(pageDto.getCaseId());
            if (caseSourceRegisterMainInfo == null) {
                throw new BusinessException("案源不存在");
            }
            caseNo = caseSourceRegisterMainInfo.getId();
            CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(pageDto.getCaseId());
            if (null != mainInfo && StringUtils.isNotBlank(mainInfo.getCaseNumber())) {
                territoryCode = mainInfo.getCaseTerritoryCode();
                caseNo = mainInfo.getCaseNumber();
            }
        } else if (Constant.STRING_2.equals(pageDto.getBusinessType())) {
            // 裁执分离直接获取execute_id
            caseNo = pageDto.getCaseId();
            //获取裁执分离的条线
            ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(pageDto.getCaseId());
            if (Objects.nonNull(executeMainInfo)) {
                if (StringUtils.isNotEmpty(executeMainInfo.getLineCode())) {
                    territoryCode = executeMainInfo.getLineCode().substring(0, 4);
                }
            }

        } else {
            CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(pageDto.getCaseId());
            if (mainInfo == null) {
                throw new BusinessException("系统异常案件为空");
            }
            territoryCode = mainInfo.getCaseTerritoryCode();
            caseNo = mainInfo.getCaseNumber();
            if (ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(mainInfo.getDataSource()) && ObjectUtils.isEmpty(caseNo)) {
                //立案审批时还没有案件编号,如果是案源转立案的,使用案源id
                caseNo = pageDto.getCaseId();
            }
        }

        param.setCaseNo(caseNo);
        param.setCaseId(pageDto.getCaseId());
        param.setAppKey(appKey);
        param.setPhone(UserUtil.getUserInfo().getPhone());
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.setSign(DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.setTimestamp(timestamp);
        String url = getEvidenceNewUrl(territoryCode);
        String response = HttpUtil.createPost(url.concat(evidencePageList)).body(JSON.toJSONString(param)).execute().body();
        JSONObject info = null;
        try {
            info = JSONObject.parseObject(response);
        } catch (Exception e) {
            log.info("证据库新对接".concat(evidencePageList).concat(" response:"), response);
            return page;
        }
        List<EvidencePageNewVo> list = new ArrayList<>();
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            JSONArray array = info.getJSONObject(DATA).getJSONArray(DL);
            page.setRecordsTotal(array.size());
            //page.setPages(array.size() / pageDto.getPageSize());
            for (int i = 0; i < array.size(); i++) {
                EvidencePageNewVo caseMainEvidenceVo = JSON.parseObject(array.getJSONObject(i).toJSONString(), EvidencePageNewVo.class);
                caseMainEvidenceVo.setCaseId(pageDto.getCaseId());
                list.add(caseMainEvidenceVo);
            }
        } else {
            log.info("证据库新对接".concat(evidencePageList).concat(" response:"), response);
        }
        if (!list.isEmpty()) {
            // 先删除
            caseMainEvidenceMapper.deleteAll(pageDto.getCaseId());
            // 保存
            List<CaseMainEvidenceVo> saveList = new ArrayList<>();
            for (EvidencePageNewVo evidence : list) {
                CaseMainEvidenceVo vo = new CaseMainEvidenceVo();
                BeanUtils.copyProperties(evidence, vo);
                saveList.add(vo);
            }
            caseMainEvidenceMapper.savaList(saveList);
            // 分页
            list = list.stream().skip((pageDto.getPageNum() - 1) * pageDto.getPageSize()).limit(pageDto.getPageSize()).collect(Collectors.toList());
            page.setData(list);
        }
        return page;
    }

    /**
     * 根据登录人获取证据库应该调用的地址
     *
     * @param
     * @return {@link String}
     * @author liyafeng
     * @date 2022/6/15
     */
    private String getEvidenceNewUrl(String territoryCode) {
        System.out.println("territoryCode:" + territoryCode);
        UserDTO userDTO = UserUtil.getUserInfo();
        String areaCode = userDTO.getAreaCode();
        System.out.println("areaCode:" + areaCode);
        String url = "";
        if (areaCode.startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(territoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(territoryCode))) {
            url = apiurl;
        } else {
            url = exceptTzUrl;
        }
        System.out.println("证据库地址=========" + url);
        return url;
    }

    /**
     * 删除 案件所有草稿
     *
     * @param caseId
     * @return
     */
    @Override
    public Boolean removeAllDraft(String caseId) {
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (mainInfo == null) {
            throw new BusinessException("系统异常案件为空");
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseNo", mainInfo.getCaseNumber());
        String url = getEvidenceNewUrl(mainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(deleteAllDraft)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        }
        log.info("证据库新对接删除案件所有草稿结果失败返回：{}", response);
        return false;
    }

    /**
     * 删除 单个草稿
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean removeDraftByUid(EvidenceDetailQueryDto dto) {
        String territoryCode = "";
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        if (null != caseMainInfo) {
            territoryCode = caseMainInfo.getCaseTerritoryCode();
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("uid", dto.getUid());
        String url = getEvidenceNewUrl(territoryCode);
        String response = HttpUtil.createPost(url.concat(deleteDraft)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接删除单个草稿结果失败返回：{}", response);
            throw new BusinessException("证据中心删除草稿失败：" + info.getString("message"));
        }
    }

    /**
     * 同步案件信息
     *
     * @param caseId
     * @return
     */
    @Override
    public Boolean saveEvent(String caseId, String caseNo) {
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (mainInfo == null) {
            throw new BusinessException("案件不存在");
        }
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        List<CaseMainDetailInfo> detailInfos = caseMainDetailInfoMapper.select(caseMainDetailInfo);
        if (detailInfos.isEmpty()) {
            throw new BusinessException("案件详情不存在");
        }
        caseMainDetailInfo = detailInfos.get(0);
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", caseId);
        param.put("caseNo", caseNo);
        param.put("caseName", mainInfo.getCaseName());
        // 案件环节 （目前是立案审批通过调用，写死）
        param.put("casePart", "02");
        CaseReasonMainRecordQueryDto caseReasonMainRecordQueryDto = new CaseReasonMainRecordQueryDto();
        caseReasonMainRecordQueryDto.setCaseId(caseId);
        caseReasonMainRecordQueryDto.setStatus("1");
        // 多案由处理
        StringJoiner caseCauseCodes = new StringJoiner(",");
        StringJoiner caseCauses = new StringJoiner(",");
        if (!TerritoryCodeEnum.RLSB.getCode().equals(mainInfo.getCaseTerritoryCode())) {
            List<CaseReasonMainRecordVo> caseReasonMainRecordVos = caseReasonMainRecordMapper.selectCaseReasonRecordList(caseReasonMainRecordQueryDto);
            if (caseReasonMainRecordVos.isEmpty()) {
                throw new BusinessException("案由信息为空");
            }
            for (CaseReasonMainRecordVo caseReason : caseReasonMainRecordVos) {
                caseCauseCodes.add(caseReason.getCaseReasonCode());
                caseCauses.add(caseReason.getCaseReasonName());
            }
        }
        param.put("caseCauseCode", caseCauseCodes.toString());
        param.put("caseCause", caseCauses.toString());
        param.put("eventType", "01");
        param.put("caseTime", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 执法人员信心
        setZfInfo(param, caseId);
        param.put("caseDesc", caseMainDetailInfo.getCaseConciseCondition());
        param.put("caseCrimePlace", caseMainDetailInfo.getCaseHappenAddressDetail());
        param.put("areaCodeCaseCrimePlace", caseMainDetailInfo.getCaseHappenAddressAreaCode());
        param.put("areaNameCaseCrimePlace", "");
        param.put("lawDeptCode", StringUtils.isNotBlank(mainInfo.getCaseOrgCode()) ? mainInfo.getCaseOrgCode().substring(13) : mainInfo.getCaseOrgCode());
        param.put("lawDeptName", mainInfo.getCaseOrgName());
        param.put("lawDeptOrgCode", mainInfo.getCaseOrgCode());
        param.put("zfDeptCode", mainInfo.getCaseDeptCode());
        param.put("zfDeptName", mainInfo.getCaseDeptName());
        param.put("caseProcessType", mainInfo.getCaseType());
        setSourceCode(mainInfo, param);
        param.put("caseSourceDate", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //立案批准人
        UserDTO userDTO = UserUtil.getUserInfo();
        if (null != userDTO) {
            param.put("filingPerson", userDTO.getRealName());
        }
        param.put("filingCode", caseNo);
        //鉴定 中止与恢复 办案期限计算
        param.put("deadline", LocalDateTime.now().plusDays(90).toLocalDate().toString());
        CaseMainInfoStatusChangeRecord record = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(caseId, CaseStatusChangeTypeEnum.SUSPEND.getCode());
        if (null != record) {
            //暂停，则原有的办案期限+（当前日期-中止日期）
            if (Constant.STRING_1.equals(record.getStatus())) {
                long days = DateUtil.calculatePastDays(record.getChangeEffectTime().toLocalDate());
                param.put("deadline", mainInfo.getCaseTimelimit().plusDays(days));
            }
            //恢复，则原有的办案期限+（恢复日期-中止日期）
        }
        param.put("filingDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 当事人信息
        setPartyInfo(caseId, param);
        //添加行政行为码
        param.put("actsCode", mainInfo.getCaseActsCode());
        String url = getEvidenceNewUrl(mainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(saveEvent)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接同步案件信息失败返回：{}", response);
        }
        return false;
    }

    /**
     * 来源编码
     *
     * @param mainInfo
     * @param param
     */
    private void setSourceCode(CaseMainInfo mainInfo, JSONObject param) {
        String caseSourceCode = "08";
        String caseSource = mainInfo.getCaseSource();
        if ("机构检测报告".equals(caseSource)) {
            caseSourceCode = "02";
        } else if ("社会举报".equals(caseSource)) {
            caseSourceCode = "03";
        } else if ("上级行政机关交办".equals(caseSource)) {
            caseSourceCode = "04";
        } else if ("下级行政机关报请".equals(caseSource)) {
            caseSourceCode = "05";
        } else if ("有关部门移送".equals(caseSource)) {
            caseSourceCode = "06";
        } else if ("非现场执法".equals(caseSource)) {
            caseSourceCode = "07";
        } else if ("巡查中发现".equals(caseSource)) {
            caseSourceCode = "08";
        }
        param.put("caseSourceType", caseSourceCode);
    }

    /**
     * 删除案件
     *
     * @param caseId
     * @return
     */
    @Override
    public Boolean removeEvent(String caseId) {
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (mainInfo == null) {
            throw new BusinessException("系统异常案件为空");
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseNo", mainInfo.getCaseNumber());
        String url = getEvidenceNewUrl(mainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(removeCase)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        }
        log.info("证据库新对接删除案件结果失败返回：{}", response);
        return false;
    }

    /**
     * 设置执法人员信息
     *
     * @param param
     * @param
     */
    private void setZfInfo(JSONObject param, String caseId) {
        CaseHandlePersonRecord handlePersonRecord = new CaseHandlePersonRecord();
        handlePersonRecord.setCaseId(caseId);
        handlePersonRecord.setStatus(Constant.STRING_1);
        List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.select(handlePersonRecord);
        if (!handlePersonRecords.isEmpty()) {
            StringJoiner stringJion = new StringJoiner("^");
            StringJoiner stringJion1 = new StringJoiner("^");
            for (CaseHandlePersonRecord caseHandlePersonRecord : handlePersonRecords) {
                if (Constant.STRING_1.equals(caseHandlePersonRecord.getHandlePersonType())) {
                    stringJion1.add(caseHandlePersonRecord.getLawEnforcementCert());
                    stringJion.add(caseHandlePersonRecord.getHandlePersonName());
                    handlePersonRecords.remove(caseHandlePersonRecord);
                    break;
                }
            }
            for (CaseHandlePersonRecord caseHandlePersonRecord : handlePersonRecords) {
                stringJion1.add(caseHandlePersonRecord.getLawEnforcementCert());
                stringJion.add(caseHandlePersonRecord.getHandlePersonName());
            }
            param.put("zfPersonnelCode", stringJion1.toString());
            param.put("zfPersonnelName", stringJion.toString());
        }
    }

    /**
     * 设置案源执法人员信息
     *
     * @param param
     * @param
     */
    private void setCaseSourceZfInfo(JSONObject param, String caseSourceId) {
        CaseSourceHandlePersonRecord caseSourceHandlePersonRecord = new CaseSourceHandlePersonRecord();
        caseSourceHandlePersonRecord.setCaseSourceId(caseSourceId);
        List<CaseSourceHandlePersonRecord> handlePersonRecords = caseSourceHandlePersonRecordMapper.select(caseSourceHandlePersonRecord);
        if (!handlePersonRecords.isEmpty()) {
            StringJoiner stringJion = new StringJoiner("^");
            StringJoiner stringJion1 = new StringJoiner("^");
            for (CaseSourceHandlePersonRecord caseHandlePersonRecord : handlePersonRecords) {
                if (Constant.STRING_1.equals(caseHandlePersonRecord.getHandlePersonType())) {
                    stringJion1.add(caseHandlePersonRecord.getLawEnforcementCert());
                    stringJion.add(caseHandlePersonRecord.getHandlePersonName());
                    handlePersonRecords.remove(caseHandlePersonRecord);
                    break;
                }
            }
            for (CaseSourceHandlePersonRecord caseHandlePersonRecord : handlePersonRecords) {
                stringJion1.add(caseHandlePersonRecord.getLawEnforcementCert());
                stringJion.add(caseHandlePersonRecord.getHandlePersonName());
            }
            param.put("zfPersonnelCode", stringJion1.toString());
            param.put("zfPersonnelName", stringJion.toString());
        }
    }

    /**
     * 当事人信息
     *
     * @param caseId
     * @param parama
     */
    private void setPartyInfo(String caseId, JSONObject parama) {
        // 多当事人改造
        List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
        if (casePartiesRecords.isEmpty()) {
            throw new BusinessException("案件当事人为空");
        }
        List<JSONObject> cpInfoList = new ArrayList<>();
        for (CasePartiesRecordVo r : casePartiesRecords) {
            JSONObject param = new JSONObject();
            param.put("cpName", r.getPartyName());
            if (PartyTypeEnum.PERSON.getCode().equals(r.getPartyType())) {
                CasePartiesPersonInfo partiesPersonInfo = casePartiesPersonInfoMapper.selectByPrimaryKey(r.getPartyId());
                param.put("cpType", "01");
                param.put("cpCertNo", partiesPersonInfo.getCertNo());
                param.put("cpCertType", EvidenceCertTypeEnum.getCodeByRelCode(partiesPersonInfo.getCertType()));
                param.put("cpTel", partiesPersonInfo.getMobile());
                param.put("addressLive", partiesPersonInfo.getAddress());
                param.put("areaCodeLive", "");
                param.put("areaNameLive", "");
            } else if (PartyTypeEnum.LEGAL.getCode().equals(r.getPartyType())) {
                //1.2 判断公司单位是当事人
                CasePartiesLegalInfo partiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(r.getPartyId());
                param.put("cpType", "02");
                param.put("cpCertNo", partiesLegalInfo.getUniscid());
                param.put("cpCertType", "001");
                param.put("cpTel", partiesLegalInfo.getPhone());
                param.put("lerepCertType", "111");
                param.put("lerepName", partiesLegalInfo.getLegalName());
                param.put("lerepCertNo", partiesLegalInfo.getLegalCertNo());
                param.put("addressRegisterd", partiesLegalInfo.getAddress());
                param.put("areaCodeRegisterd", "");
                param.put("areaNameRegisterd", "");
                param.put("addressOperating", partiesLegalInfo.getAddress());
                param.put("areaCodeOperating", "");
                param.put("areaNameOperating", "");
                param.put("contactName", partiesLegalInfo.getLegalName());
                param.put("position", partiesLegalInfo.getJob());
            }
            cpInfoList.add(param);
        }
        parama.put("cpInfoList", cpInfoList);
    }

    /**
     * 案源当事人信息
     *
     * @param caseSourceId
     * @param params
     */
    private void setCaseSourcePartyInfo(String caseSourceId, JSONObject params) {
        Example partyExample = new Example(CaseSourcePartyInfo.class);
        partyExample.createCriteria().andEqualTo("caseSourceId", caseSourceId);
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(partyExample);
        List<JSONObject> cpInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(caseSourcePartyInfos)) {
            for (CaseSourcePartyInfo r : caseSourcePartyInfos) {
                JSONObject param = new JSONObject();
                param.put("cpName", r.getPartyName());
                if (PartyTypeEnum.PERSON.getCode().equals(r.getPartyType())) {
                    CaseSourcePartyInfo partiesPersonInfo = caseSourcePartyInfoMapper.selectByPrimaryKey(r.getId());
                    if (ObjectUtil.isNotNull(partiesPersonInfo)) {
                        param.put("cpType", "01");
                        param.put("cpCertNo", partiesPersonInfo.getPartyIdentityCode());
                        param.put("cpCertType", EvidenceCertTypeEnum.getCodeByRelCode(partiesPersonInfo.getPartyIdentityType()));
                        param.put("cpTel", partiesPersonInfo.getMobile());
                        param.put("addressLive", partiesPersonInfo.getAddress());
                        param.put("areaCodeLive", "");
                        param.put("areaNameLive", "");
                    }
                } else if (PartyTypeEnum.LEGAL.getCode().equals(r.getPartyType())) {
                    //1.2 判断公司单位是当事人
                    CaseSourcePartyInfo partiesLegalInfo = caseSourcePartyInfoMapper.selectByPrimaryKey(r.getId());
                    if (ObjectUtil.isNotNull(partiesLegalInfo)) {
                        param.put("cpType", "02");
                        param.put("cpCertNo", partiesLegalInfo.getPartyIdentityCode());
                        param.put("cpCertType", "001");
                        param.put("cpTel", partiesLegalInfo.getMobile());
                        param.put("lerepCertType", "111");
                        param.put("lerepName", partiesLegalInfo.getLegalName());
                        param.put("lerepCertNo", partiesLegalInfo.getLegalCertNo());
                        param.put("addressRegisterd", partiesLegalInfo.getAddress());
                        param.put("areaCodeRegisterd", "");
                        param.put("areaNameRegisterd", "");
                        param.put("addressOperating", partiesLegalInfo.getAddress());
                        param.put("areaCodeOperating", "");
                        param.put("areaNameOperating", "");
                        param.put("contactName", partiesLegalInfo.getLegalName());
                        param.put("position", partiesLegalInfo.getJob());
                    }
                }
                cpInfoList.add(param);
            }
            params.put("cpInfoList", cpInfoList);
        }
    }

    /**
     * 获得按钮链接接口
     *
     * @param dto
     * @return
     */
    @Override
    public String getButtonUrl(EvidenceButtonUrlQueryDto dto) {
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("userName", UserUtil.getUserInfo().getPhone());
        param.put("deptCode", UserUtil.getUserInfo().getDeptCode());
        JSONObject baseInfoRequest = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.add(UserUtil.getUserInfo().getUserId().toString());
        baseInfoRequest.put("userIds", userIds);
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        if (baseInfo.isEmpty()) {
            param.put("executorId", "");
        } else {
            param.put("executorId", baseInfo.get(0).getZfCertList().get(0).getZfCertNo());
        }
        param.put("linkType", dto.getLinkType());
        if (Arrays.asList(EvidenceOperateTypeEnum.T00.getLinkType(), EvidenceOperateTypeEnum.T01.getLinkType()).contains(dto.getLinkType())) {
            //调查（询问）笔录 笔录 ，现场勘验（检查）笔录 跳转固定笔录地址
            param.put("linkType","noteTaking_transition");
        }

        Map paramMap = new HashMap<>(16);
        String caseTerritoryCode = "";
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        if (null != caseMainInfo) {
            caseTerritoryCode = caseMainInfo.getCaseTerritoryCode();
        }
        // 笔录增加案件编号
        String noteTaking = "noteTaking_transition";
        if (noteTaking.equals(dto.getLinkType())) {
            //CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
//            if (caseMainInfo == null) {
//                throw new BusinessException("系统异常案件为空");
//            }
//            paramMap.put("caseNo", caseMainInfo.getCaseNumber());
            if (Objects.nonNull(caseMainInfo)) {
                paramMap.put("caseNo", caseMainInfo.getCaseNumber());
            }
        }
        /*List<SysDepartParam> list=new ArrayList<>();
        SysDepartParam sysDepartParam=new SysDepartParam();
        Example example = new Example(SysDepartParam.class);
        example.createCriteria().andEqualTo("orgCode", UserUtil.getUserInfo().getOrgCode()).andIsNull("deptCode");
        list = sysDepartParamMapper.selectByExample(example);
        String isConfigDept=Constant.STRING_0;
        if(!ObjectUtils.isEmpty(list)){
            isConfigDept=list.get(0).getIsConfigDept();
            sysDepartParam=list.get(0);
        }
        //若配置二级查询二级配置
        if(Constant.STRING_1.equals(isConfigDept)){
            Example deptExample = new Example(SysDepartParam.class);
            deptExample.createCriteria().andEqualTo("orgCode", UserUtil.getUserInfo().getOrgCode()).andEqualTo("deptCode",UserUtil.getUserInfo().getDeptCode());
            list = sysDepartParamMapper.selectByExample(example);
            if(!ObjectUtils.isEmpty(list)){
                sysDepartParam=list.get(0);
            }
        }*/
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(UserUtil.getUserInfo().getOrgCode(), UserUtil.getUserInfo().getDeptCode());
        paramMap.put("caseId", dto.getCaseId());
        paramMap.put("uid", dto.getUid());
        paramMap.put("orgWritName", sysDepartParam == null ? null : sysDepartParam.getOrgStandardName());
        paramMap.put("caseTerritoryCode", getLineCode(dto.getCaseId()));
        param.put("paramMap", paramMap);
        String url = getEvidenceNewUrl(getLineCode(dto.getCaseId()));
        String response = HttpUtil.createPost(url.concat(buttonUrl)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            String evidenceButtonUrl = info.getString("data");
            //全省简案快办 地址拼接上类别
            if(ObjectUtil.isNotEmpty(caseMainInfo) && CaseTypeEnum.FAST_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())){
                evidenceButtonUrl= evidenceButtonUrl+"&caseType="+caseMainInfo.getCaseType()+"&recordType="+dto.getLinkType();
            }
            return evidenceButtonUrl;
        } else {
            log.info("证据库新对接免登信息失败返回：{}", response);
            throw new BusinessException("证据中心：" + info.getString("message"));
        }

    }

    /**
     * 获取条线code
     *
     * @param caseId
     * @return
     */
    private String getLineCode(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (Objects.nonNull(caseMainInfo)) {
            return caseMainInfo.getCaseTerritoryCode();
        }
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseId);
        if (Objects.nonNull(caseSourceRegisterMainInfo)) {
            if (StringUtils.isNotEmpty(caseSourceRegisterMainInfo.getLineCode())) {
                return caseSourceRegisterMainInfo.getLineCode().substring(0, 4);
            }
        }
        //获取裁执分离得条线
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(caseId);
        if (Objects.nonNull(executeMainInfo)) {
            if (StringUtils.isNotEmpty(executeMainInfo.getLineCode())) {
                return executeMainInfo.getLineCode().substring(0, 4);
            }
        }

        return null;
    }

    /**
     * 更新案件环节
     *
     * @param caseId
     * @return
     */
    @Override
    public Boolean updateCaseNode(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("系统异常案件为空");
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseNo", caseMainInfo.getCaseNumber());
        // 案件环节（01:立案、02:调查取证、03:处罚告知、04:处罚决定、05:处罚执行、06:结案、07: 案件延期、08:案件终止、09:案件中止、10:案件恢复、11:销案、12:移送）
        param.put("casePart", caseMainInfo.getCaseNumber());
        // 阶段
        // 立案
        //调查取证
        //处罚告知
        //处罚决定
        //结案
        String la = "立案";
        String cfdcqzs = "调查取证";
        String cfgz = "处罚告知";
        String cfjd = "处罚决定";
        String cfja = "结案";
        String zx = "执行";
        String zz = "中止";
        String hf = "恢复";
        String ys = "移送";
        String xa = "销案";
        String yq = "延期";
        String zzf = "终止";
        if (caseMainInfo.getCaseCurrentStageName().contains(ys)) {
            param.put("casePart", "12");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(zzf)) {
            param.put("casePart", "08");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(xa)) {
            param.put("casePart", "11");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(yq)) {
            param.put("casePart", "07");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(la)) {
            param.put("casePart", "01");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(cfdcqzs)) {
            param.put("casePart", "02");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(cfgz)) {
            param.put("casePart", "03");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(cfjd)) {
            param.put("casePart", "04");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(cfja)) {
            param.put("casePart", "06");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(zz)) {
            param.put("casePart", "09");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(zx)) {
            param.put("casePart", "05");
        }
        if (caseMainInfo.getCaseCurrentStageName().contains(hf)) {
            param.put("casePart", "10");
        }
        String url = getEvidenceNewUrl(caseMainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(updateCaseNode)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        }
        log.info("证据库新对接更新案件环节失败返回：{}", response);
        return false;
    }

    /**
     * 保存鉴定相关文书
     *
     * @return
     */
    @Override
    public Boolean saveAppraisalDoc() {
        // 定时任务扫描 调用
        // 查询 文书记录和鉴定报告的表 查询前一天已送达的文书 和 拼参数调用接口
        List<EvidenceAppraisalDocInfoVo> vos = caseDocumentAppraisalYjgzsMapper.getEvidenceSyncAppraisalDocInfo(LocalDate.now().minusDays(1L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        if (!vos.isEmpty()) {
            for (EvidenceAppraisalDocInfoVo vo : vos) {
                try {
                    CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(vo.getCaseId());
                    JSONObject param = new JSONObject();
                    param.put("appKey", appKey);
                    // 防止时间戳不一致
                    String timestamp = getTimestamp();
                    param.put("timestamp", timestamp);
                    param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
                    param.put("evidenceUid", vo.getUid());
                    JSONArray array = new JSONArray();
                    JSONObject appraisalDocDTO = new JSONObject();
                    appraisalDocDTO.put("fileType", "01");
                    appraisalDocDTO.put("fileName", "鉴定意见告知书");
                    appraisalDocDTO.put("operateTime", vo.getSentTime());
                    JSONObject baseInfoRequest = new JSONObject();
                    List<String> userIds = new ArrayList<>();
                    userIds.add(vo.getSendId());
                    baseInfoRequest.put("userIds", userIds);
                    List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
                    if (baseInfo.isEmpty()) {
                        log.info("保存鉴定相关文书查询送达操作人用户手机号失败uid：{}", vo.getUid());
                        //continue;
                    }
                    appraisalDocDTO.put("phone", baseInfo.get(0).getPhone());
                    InputStream is = null;
                    if (StringUtils.isNotBlank(vo.getSignUrl())) {
                        is = HttpUtil.createGet(vo.getSignUrl()).execute().bodyStream();
                    } else {
                        is = HttpUtil.createGet(vo.getSealUrl()).execute().bodyStream();
                    }
                    // 文件转为base64
                    appraisalDocDTO.put("fileBase64", Base64.encode(is));
                    array.add(appraisalDocDTO);
                    param.put("docList", array);
                    String url = getEvidenceNewUrl(caseMainInfo.getCaseTerritoryCode());
                    String response = HttpUtil.createPost(url.concat(saveAppraisalDoc)).body(param.toJSONString()).execute().body();
                    JSONObject info = JSONObject.parseObject(response);
                    if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
                        log.info("保存鉴定相关文书同步成功1条，uid：{}", vo.getUid());
                    } else {
                        log.info("保存鉴定相关文书同步失败1条，uid：{}，返回：{}", vo.getUid(), response);
                    }
                } catch (Exception e) {
                    log.info("保存鉴定相关文书同步失败，uid：{}", vo.getUid());
                }
            }
        }

        return false;
    }

    /**
     * 保存过程文书
     *
     * @param caseId
     * @param documentCatalogCode
     * @return
     */
    @Override
    public Boolean saveCaseProcessDocument(String caseId, String documentCatalogCode) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("系统异常案件为空");
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseNo", caseMainInfo.getCaseNumber());
        Example example = new Example(CaseDocumentRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<CaseDocumentRecord> records = caseDocumentRecordMapper.selectByExample(example);
        if (!records.isEmpty()) {
            Example exampleParam = new Example(ConfigBusiParamDocumentInfo.class);
            exampleParam.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
            List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(exampleParam);
            param.put("docCode", records.get(0).getDocumentNumber());
            param.put("title", configBusiParamDocumentInfos.get(0).getDocumentCatalogName());
            param.put("generationDate", records.get(0).getDocumentCreateTime().toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            param.put("classification", configBusiParamDocumentInfos.get(0).getDocumentCatalogName());
            InputStream is = null;
            if (StringUtils.isNotBlank(records.get(0).getDocumentUrlAfterSeal())) {
                is = HttpUtil.createGet(records.get(0).getDocumentUrlAfterSeal()).execute().bodyStream();
            } else {
                is = HttpUtil.createGet(records.get(0).getDocumentUrl()).execute().bodyStream();
            }
            // 文件转为base64
            param.put("contentBase64", Base64.encode(is));
            String url = getEvidenceNewUrl(caseMainInfo.getCaseTerritoryCode());
            String response = HttpUtil.createPost(url.concat(saveCaseProcessDocument)).body(param.toJSONString()).execute().body();
            JSONObject info = JSONObject.parseObject(response);
            if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
                return true;
            }
            log.info("证据库新对接保存过程文书结果失败返回：{}", response);
        }
        return false;
    }

    /**
     * 保存案件结果  定时任务调用
     *
     * @param caseId
     * @return
     */
    @Override
    public Boolean saveCaseResultInfo(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("案件不存在");
        }
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        List<CaseMainDetailInfo> detailInfos = caseMainDetailInfoMapper.select(caseMainDetailInfo);
        if (detailInfos.isEmpty()) {
            throw new BusinessException("案件详情不存在");
        }
        caseMainDetailInfo = detailInfos.get(0);
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseNo", caseMainInfo.getCaseNumber());
        param.put("laApprovalTime", caseMainInfo.getCaseRegistTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        param.put("laDate", caseMainInfo.getCaseCreateTime().toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        param.put("closeDate", caseMainDetailInfo.getCaseFinishDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        param.put("caseResult", StringUtils.isNotBlank(caseMainDetailInfo.getExecuteConditionDesc()) ? caseMainDetailInfo.getExecuteConditionDesc() : caseMainDetailInfo.getCaseFinishConditionIllustrate());
        String url = getEvidenceNewUrl(caseMainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(saveCaseResultInfo)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        }
        log.info("证据库新对接保存案件结果失败返回：{}", response);
        return false;
    }

    @Override
    public Boolean removeEvidenceByUid(EvidenceDetailQueryDto dto) {
        String territoryCode = "";
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        if (null != caseMainInfo) {
            territoryCode = caseMainInfo.getCaseTerritoryCode();
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("uid", dto.getUid());
        String url = getEvidenceNewUrl(territoryCode);
        String response = HttpUtil.createPost(url.concat(deleteEvidence)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接删除单个证据结果失败返回：{}", response);
            throw new BusinessException("证据中心删除证据失败：" + info.getString("message"));
        }
    }

    @Override
    public Boolean updateCpInfo(String caseId) {
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", caseId);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (caseMainInfo == null) {
            throw new BusinessException("案件不存在");
        }
        param.put("caseNo", caseMainInfo.getCaseNumber());
        setPartyInfo(caseId, param);
        String url = getEvidenceNewUrl(caseMainInfo.getCaseTerritoryCode());
        String response = HttpUtil.createPost(url.concat(updateCpInfo)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        }
        log.info("证据库更新当事人信息结果失败返回：{}", response);
        return false;
    }

    /**
     * 重新推送案件信息到证据库
     *
     * @param dto
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/7/11
     */
    @Override
    public boolean reSaveEvent(EventReSaveDto dto) {
        String caseId = dto.getCaseId();
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (mainInfo == null) {
            throw new BusinessException("案件不存在");
        }
        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        List<CaseMainDetailInfo> detailInfos = caseMainDetailInfoMapper.select(caseMainDetailInfo);
        if (detailInfos.isEmpty()) {
            throw new BusinessException("案件详情不存在");
        }
        caseMainDetailInfo = detailInfos.get(0);
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", caseId);
        param.put("caseNo", mainInfo.getCaseNumber());
        param.put("caseName", mainInfo.getCaseName());
        // 案件环节 （目前是立案审批通过调用，写死）
        param.put("casePart", "02");
        CaseReasonMainRecordQueryDto caseReasonMainRecordQueryDto = new CaseReasonMainRecordQueryDto();
        caseReasonMainRecordQueryDto.setCaseId(caseId);
        caseReasonMainRecordQueryDto.setStatus("1");
        //List<CaseReasonMainRecordVo> caseReasonMainRecordVos = caseReasonMainRecordMapper.selectCaseReasonRecordList(caseReasonMainRecordQueryDto);
        /*if (caseReasonMainRecordVos.isEmpty()) {
            throw new BusinessException("案由信息为空");
        }*/
        // 多案由处理
        StringJoiner caseCauseCodes = new StringJoiner(",");
        StringJoiner caseCauses = new StringJoiner(",");
        if (!TerritoryCodeEnum.RLSB.getCode().equals(mainInfo.getCaseTerritoryCode())) {
            List<CaseReasonMainRecordVo> caseReasonMainRecordVos = caseReasonMainRecordMapper.selectCaseReasonRecordList(caseReasonMainRecordQueryDto);
            if (caseReasonMainRecordVos.isEmpty()) {
                throw new BusinessException("案由信息为空");
            }
            for (CaseReasonMainRecordVo caseReason : caseReasonMainRecordVos) {
                caseCauseCodes.add(caseReason.getCaseReasonCode());
                caseCauses.add(caseReason.getCaseReasonName());
            }
        }
        param.put("caseCauseCode", caseCauseCodes.toString());
        param.put("caseCause", caseCauses.toString());
        param.put("eventType", "01");
        param.put("caseTime", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 执法人员信息
        setZfInfo(param, caseId);
        param.put("caseDesc", caseMainDetailInfo.getCaseConciseCondition());
        param.put("caseCrimePlace", caseMainDetailInfo.getCaseHappenAddressDetail());
        param.put("areaCodeCaseCrimePlace", caseMainDetailInfo.getCaseHappenAddressAreaCode());
        param.put("areaNameCaseCrimePlace", "");
        param.put("lawDeptCode", StringUtils.isNotBlank(mainInfo.getCaseOrgCode()) ? mainInfo.getCaseOrgCode().substring(13) : mainInfo.getCaseOrgCode());
        param.put("lawDeptName", mainInfo.getCaseOrgName());
        param.put("lawDeptOrgCode", mainInfo.getCaseOrgCode());
        param.put("zfDeptCode", mainInfo.getCaseDeptCode());
        param.put("zfDeptName", mainInfo.getCaseDeptName());
        param.put("caseProcessType", mainInfo.getCaseType());
        setSourceCode(mainInfo, param);
        param.put("caseSourceDate", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //立案批准人
        param.put("filingPerson", "");
        //查询审批人信息
        Example example = new Example(CaseApprovalCompleteRecord.class);
        example.createCriteria().andEqualTo("caseId", mainInfo.getId()).andEqualTo("approvalStatus", AuditStatusConstant.AUDIT_STATUS_AGREE).andLike("documentId", "LASPB");
        example.setOrderByClause("approval_time desc");
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(example);
        if (null != caseApprovalCompleteRecords && caseApprovalCompleteRecords.size() > 0) {
            param.put("filingPerson", caseApprovalCompleteRecords.get(0).getApprovalUserName());
        }

        param.put("filingCode", mainInfo.getCaseNumber());
        //鉴定 中止与恢复 办案期限计算
        param.put("deadline", LocalDateTime.now().plusDays(90).toLocalDate().toString());
        CaseMainInfoStatusChangeRecord record = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(caseId, CaseStatusChangeTypeEnum.SUSPEND.getCode());
        if (null != record) {
            //暂停，则原有的办案期限+（当前日期-中止日期）
            if (Constant.STRING_1.equals(record.getStatus())) {
                long days = DateUtil.calculatePastDays(record.getChangeEffectTime().toLocalDate());
                param.put("deadline", mainInfo.getCaseTimelimit().plusDays(days));
            }
            //恢复，则原有的办案期限+（恢复日期-中止日期）
        }
        //param.put("filingDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        param.put("filingDate", mainInfo.getCaseRegistTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 当事人信息
        setPartyInfo(caseId, param);
        //添加行政行为码
        param.put("actsCode", mainInfo.getCaseActsCode());
        //String url=getEvidenceNewUrl();
        String orgCode = mainInfo.getCaseOrgCode();
        String areaCode = orgCode.split("_")[0];
        String url = "";
        if (areaCode.startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(mainInfo.getCaseTerritoryCode()) || TerritoryCodeEnum.XZJD.getCode().equals(mainInfo.getCaseTerritoryCode()))) {
            url = apiurl;
        } else {
            url = exceptTzUrl;
        }
        String response = HttpUtil.createPost(url.concat(saveEvent)).body(param.toJSONString()).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接同步案件信息失败返回：{}", response);
        }
        return false;
    }

    /**
     * 新增案源事件
     *
     * @param dto
     * @return
     */
    @Override
    public boolean saveCaseSourceEvent(CaseSourceEventSaveDto dto) {
        String territoryCode = dto.getTerritoryCode();
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(dto.getCaseSourceId());
        if (StringUtils.isBlank(territoryCode)) {
            if (null != caseSourceRegisterMainInfo) {
                territoryCode = caseSourceRegisterMainInfo.getLineCode().substring(0, 4);
            }
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        String url = exceptTzUrl;
        if (userDTO.getAreaCode().startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(territoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(territoryCode))) {
            url = apiurl;
        }
        System.out.println("案源事件url:----------------" + url);
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", dto.getCaseSourceId());
        param.put("caseNo", dto.getCaseSourceId());
        param.put("caseName", dto.getCaseSourceName());
        param.put("casePart", "02");
        param.put("eventType", "98");
        // 执法人员信息
        setCaseSourceZfInfo(param, dto.getCaseSourceId());
        // 当事人信息
        setCaseSourcePartyInfo(dto.getCaseSourceId(), param);
        log.info(param.toJSONString());
        param.put("lawDeptCode", StringUtils.isNotBlank(caseSourceRegisterMainInfo.getHandleOrgCode()) ? caseSourceRegisterMainInfo.getHandleOrgCode().substring(13) : caseSourceRegisterMainInfo.getHandleOrgCode());
        param.put("lawDeptName", caseSourceRegisterMainInfo.getHandleOrgName());
        param.put("lawDeptOrgCode", caseSourceRegisterMainInfo.getHandleOrgCode());
        param.put("zfDeptCode", caseSourceRegisterMainInfo.getHandleDeptCode());
        param.put("zfDeptName", caseSourceRegisterMainInfo.getHandleDeptName());
        String response = HttpUtil.createPost(url.concat(saveCaseSourceEvent)).body(param.toJSONString()).execute().body();
        log.info("===============================================" + url.concat(saveCaseSourceEvent));
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接同步案件信息失败返回：{}", response);
        }
        return false;
    }

    /**
     * 【V1.3.2】描述：向证据库同步部门信息变更信息
     * 办案系统部门信息变化的时调用接口，更新相关数据
     *
     * @param deptInfoSyncDto 部门信息同步dto
     * @return {@link String }
     * @author shishengyao
     * @date 2022/07/20
     */
    @Override
    public Map<String, Object> syncDeptInfoToEvidenceShare(DeptInfoSyncDto deptInfoSyncDto) {
        if (ObjectUtil.isEmpty(deptInfoSyncDto.getDeptCode())) {
            throw new BusinessException("部门code不能为空");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", "true");
        resultMap.put("message", "操作成功");
        resultMap.put("code", Result.DEFAULT_SUCCESS);
        //调用证据库接口同步部门更新数据
        log.info("syncDeptInfoToEvidenceShare start!");
        JSONObject param = new JSONObject();
        param.put("deptCode", deptInfoSyncDto.getDeptCode());
        if (deptInfoSyncDto.getUniqueCode() != null) {
            param.put("uniqueCode", deptInfoSyncDto.getUniqueCode());
        }
        if (deptInfoSyncDto.getAddress() != null) {
            param.put("address", deptInfoSyncDto.getAddress());
        }
        if (deptInfoSyncDto.getDeptDocName() != null) {
            param.put("deptDocName", deptInfoSyncDto.getDeptDocName());
        }
        if (deptInfoSyncDto.getSealCode() != null) {
            param.put("sealCode", deptInfoSyncDto.getSealCode());
        }
        if (deptInfoSyncDto.getDeptDocName() != null) {
            param.put("deptDocName", deptInfoSyncDto.getDeptDocName());
        }
        if (deptInfoSyncDto.getType() != null) {
            param.put("type", deptInfoSyncDto.getType());
        }
        // 以下内容处罚不更新
        //param.put("enabled",sysDepartParam.get());
        //param.put("areaCode",sysDepartParam.getAreaCode());
        // param.put("remark",sysDepartParam.getRemark());
        //param.put("deptName","");
        String timestamp = String.valueOf(System.currentTimeMillis());
//        param.put("appKey", appKey);
//        param.put("sign", DigestUtils.md5DigestAsHex((appKey + appSecret + timestamp).getBytes(StandardCharsets.UTF_8)));
//        param.put("timestamp", timestamp);
        Map<String, String> headers = HeaderUtil.headerInfo();
        String url = exceptTzUrl + syncDeptInfo;
        try {
            String response = HttpUtil.createPost(url).body(param.toJSONString()).headerMap(headers, true).execute().body();
            JSONObject info = JSONObject.parseObject(response);
            System.out.println(info.toJSONString());
            int code = info.getInteger("code");
            if (200 == code) {
                String data = info.getString("data");
                log.info("syncDeptInfoToEvidenceShare success,----url:{},----param:{}, -----result:{}", url, param.toJSONString(), info);
            } else {
                resultMap.put("success", "false");
                resultMap.put("message", info.getString("message"));
                resultMap.put("code", Result.DEFAULT_ERROR);
                log.info("syncDeptInfoToEvidenceShare fail, ----url:{},------param:{}, ----- result:{}", url, param.toJSONString(), info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("success", "false");
            resultMap.put("message", "系统异常，" + e.getMessage());
            resultMap.put("code", Result.DEFAULT_ERROR);
        }
        return resultMap;
    }

    /**
     * 描述： 更新执法人员签名
     *
     * @author: zhengqiang
     * @date: 2022/8/5
     * @param: lawEnforcerDto
     **/
    @Override
    public boolean updateLawEnforcer(LawEnforcerDto lawEnforcerDto) {
        boolean flag = false;
        Map<String, String> headers = HeaderUtil.headerInfo();
        try {
            log.info("updateLawEnforcer start,----param:{}", JSONObject.toJSONString(lawEnforcerDto));
            String response = HttpUtil.createPost(apiurl + updateLawEnforcer).body(JSONObject.toJSONString(lawEnforcerDto)).headerMap(headers, true).execute().body();
            JSONObject info = JSONObject.parseObject(response);
            int code = info.getInteger("code");
            if (200 == code) {
                log.info("updateLawEnforcer success, result:{}", info);
                flag = true;
            } else {
                log.info("updateLawEnforcer fail, result:{}", info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("updateLawEnforcer error", e);
        }
        return flag;
    }

    /**
     * 描述： 获取查看证据链接
     *
     * @return {@link String}
     * @author: zhengqiang
     * @date: 2022/8/25
     * @param: evidenceUid
     * @param: linkType
     **/
    @Override
    public String getEvidenceLink(String evidenceUid, String linkType) {
        String url = apiurl;
        if (!UserUtil.getUserInfo().getAreaCode().startsWith("3310")) {
            url = exceptTzUrl;
        }
        ThirdAppLoginRequest request = new ThirdAppLoginRequest();
        request.setLinkType(linkType);

        String timestamp = String.valueOf(System.currentTimeMillis());
        String sign = DigestUtils.md5DigestAsHex((appKey + appSecret + timestamp).getBytes(StandardCharsets.UTF_8));
        request.setAppKey(appKey);
        request.setSign(sign);
        request.setTimestamp(timestamp);

        UserDTO userInfo = UserUtil.getUserInfo();
        request.setUserName(userInfo.getPhone());
        request.setDeptCode(userInfo.getDeptCode());

        Map<String, Object> paramMap = Collections.singletonMap("uid", evidenceUid);
        request.setParamMap(paramMap);
        JSONObject jsonRequest = JSONObject.parseObject(JSONObject.toJSONString(request));
        log.info("请求第三方应用免登证据中心返回链接地址接口入参：{}", jsonRequest);
        String response = null;
        try {
            response = HttpUtil.createPost(url + buttonUrl).body(JSONObject.toJSONString(request)).execute().body();
            log.info("请求第三方应用免登证据中心返回链接地址接口出参：", response);
            if (!ObjectUtils.isEmpty(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                if (String.valueOf(Result.DEFAULT_SUCCESS).equals(jsonObject.getString("code"))) {
                    return jsonObject.getString("data");
                }
            }
        } catch (HttpException e) {
            e.printStackTrace();
            log.error("请求第三方应用免登证据中心返回链接地址接口异常：{}", e);
        }
        return null;
    }

    @Override
    public boolean saveExecuteEvent(ExecuteEventSaveDto dto) {
        String caseTerritoryCode = "";
        String url = exceptTzUrl;
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getExecuteId());
        if (Objects.nonNull(mainInfo)) {
            if (StringUtils.isNotEmpty(mainInfo.getLineCode())) {
                caseTerritoryCode = mainInfo.getLineCode().substring(0, 4);
            }
        }

        //获取裁执分离的条线
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(dto.getExecuteId());
        if (Objects.nonNull(executeMainInfo)) {
            if (StringUtils.isNotEmpty(executeMainInfo.getLineCode())) {
                caseTerritoryCode = executeMainInfo.getLineCode().substring(0, 4);
            }
        }
        if (UserUtil.getUserInfo().getAreaCode().startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(caseTerritoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(caseTerritoryCode))) {
            url = apiurl;
        }
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", dto.getExecuteId());
        param.put("caseNo", dto.getExecuteId());
        param.put("caseName", dto.getExecuteName());
        param.put("casePart", "02");
        param.put("eventType", "97");
        // 执法人员信息
        setExecuteZfInfo(param, dto.getExecuteId());
        // 当事人信息
        setExecutePartyInfo(dto.getExecuteId(), param);
        log.info(param.toJSONString());
        String response = HttpUtil.createPost(url.concat(saveCaseSourceEvent)).body(param.toJSONString()).execute().body();
        log.info("===============================================" + url.concat(saveCaseSourceEvent));
        JSONObject info = JSONObject.parseObject(response);
        log.info(info.toJSONString());
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接同步案件信息失败返回：{}", response);
        }
        return false;
    }

    /**
     * 描述: 设置裁执分离执法人员信息
     *
     * @param param
     * @param executeId
     * @return void
     * @author zhanghongqiang
     * @Date 2022/9/5
     */
    private void setExecuteZfInfo(JSONObject param, String executeId) {
        ExecuteHandlePersonRecord executeHandlePersonRecord = new ExecuteHandlePersonRecord();
        executeHandlePersonRecord.setExecuteId(executeId);
        List<ExecuteHandlePersonRecord> handlePersonRecords = executeHandlePersonRecordMapper.select(executeHandlePersonRecord);
        if (!handlePersonRecords.isEmpty()) {
            StringJoiner stringJion = new StringJoiner("^");
            StringJoiner stringJion1 = new StringJoiner("^");
            for (ExecuteHandlePersonRecord handlePersonRecord : handlePersonRecords) {
                if (Constant.STRING_1.equals(handlePersonRecord.getHandlePersonType())) {
                    stringJion1.add(handlePersonRecord.getLawEnforcementCert());
                    stringJion.add(handlePersonRecord.getHandlePersonName());
                    handlePersonRecords.remove(handlePersonRecord);
                    break;
                }
            }
            for (ExecuteHandlePersonRecord handlePersonRecord : handlePersonRecords) {
                stringJion1.add(handlePersonRecord.getLawEnforcementCert());
                stringJion.add(handlePersonRecord.getHandlePersonName());
            }
            param.put("zfPersonnelCode", stringJion1.toString());
            param.put("zfPersonnelName", stringJion.toString());
        }
    }

    /**
     * 描述: 裁执分离当事人信息
     *
     * @param executeId
     * @param params
     * @return void
     * @author zhanghongqiang
     * @Date 2022/9/5
     */
    private void setExecutePartyInfo(String executeId, JSONObject params) {
        Example partyExample = new Example(ExecutePartyInfo.class);
        partyExample.createCriteria().andEqualTo("executeId", executeId);
        List<ExecutePartyInfo> executePartyInfos = executePartyInfoMapper.selectByExample(partyExample);
        List<JSONObject> cpInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(executePartyInfos)) {
            for (ExecutePartyInfo r : executePartyInfos) {
                JSONObject param = new JSONObject();
                param.put("cpName", r.getPartyName());
                // 判断是单位还还是个人
                if (PartyTypeEnum.PERSON.getCode().equals(r.getPartyType())) {
                    param.put("cpType", "01");
                    param.put("cpCertNo", r.getPartyIdentityCode());
                    // TODO 看法院编码
                    param.put("cpCertType", EvidenceCertTypeEnum.getCodeByRelCode(r.getPartyIdentityType()));
                    param.put("addressLive", r.getAddress());
                    param.put("areaCodeLive", "");
                    param.put("areaNameLive", "");
                } else if (PartyTypeEnum.LEGAL.getCode().equals(r.getPartyType())) {
                    param.put("cpType", "02");
                    param.put("cpCertNo", r.getPartyIdentityCode());
                    param.put("cpCertType", "001");
                    param.put("lerepCertType", "111");
                    param.put("lerepName", r.getLegalName());
                    param.put("lerepCertNo", r.getLegalCertNo());
                    param.put("addressRegisterd", r.getAddress());
                    param.put("areaCodeRegisterd", "");
                    param.put("areaNameRegisterd", "");
                    param.put("addressOperating", r.getAddress());
                    param.put("areaCodeOperating", "");
                    param.put("areaNameOperating", "");
                    param.put("contactName", r.getLegalName());

                }
                cpInfoList.add(param);
            }
            params.put("cpInfoList", cpInfoList);
        }
    }

    /**
     * 描述：获取证据详情
     *
     * @param caseId 用例id
     * @return {@link List<CaseCriminalTransferFileVo> }
     * @author shishengyao
     * @date 2022/10/11
     */
    @Override
    public List<Map> getEvidenceDetailList(String caseId) {
        log.info("getEvidenceByCaseId 调用证据库证据接口 start");
        Result result = null;
        try {
            String caseTerritoryCode = "";
            String url = exceptTzUrl;
            String areaCode = "";
            CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            if (Objects.nonNull(mainInfo)) {
                if (StringUtils.isNotEmpty(mainInfo.getLineCode())) {
                    caseTerritoryCode = mainInfo.getLineCode().substring(0, 4);
                }
                areaCode = mainInfo.getCaseAreaCode();
            }

            if (ObjectUtil.isNotEmpty(areaCode) && areaCode.startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(caseTerritoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(caseTerritoryCode))) {
                url = apiurl;
            }

            Map<String, Object> urlParam = new HashMap<>();
            urlParam.put("caseId", caseId);
            log.info("getListCataIdBy -- 入参: {}", urlParam);
            String response = HttpUtil.createGet(url.concat(getEvidenceByCaseId)).form(urlParam).execute().body();
            log.info("getListCataIdBy -- 出参: {}", response);
            result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())) {
                Object data = result.getData();
                List<Map> arrayLists = JSON.parseArray(JSON.toJSONString(data), Map.class);
                return arrayLists;
            }
        } catch (Exception e) {
            log.error("getEvidenceByCaseId 调用证据库证据接口报错: {}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 【AJ-V1.1.1】描述： 根据案件id删除证据
     *
     * @return {@link Boolean}
     * @author: zhengqiang
     * @date: 2023/3/9
     * @param: caseId
     **/
    @Override
    public Boolean deleteEvidenceByCaseId(String caseId) {
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", caseId);
        log.info("删除证据请求参数:{}", param);
        String response = HttpUtil.createPost(exceptTzUrl.concat(deleteEvidenceByCaseId)).body(param.toJSONString()).execute().body();
        log.info("删除证据返回参数:{}", response);
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接根据案件id删除证据结果失败返回：{}", response);
            throw new BusinessException("证据中心删除证据失败：" + info.getString("message"));
        }
    }

    /**
     * 查询证据树
     *
     * @param caseId
     * @return
     */
    @Override
    public List<EvidenceInfo> getCaseEvidenceInfo(String caseId, Boolean filterFlag) {
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", caseId);
        if (filterFlag){
            //需要过滤 传1
            param.put("filterFlag", "1");
        }
        log.info("查询证据树证据请求参数:{}", param);
        String response = HttpUtil.createPost(exceptTzUrl.concat(getCaseEvidenceInfo)).body(param.toJSONString()).execute().body();
        log.info("查询证据树证据返回参数:{}", response);
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return info.getJSONArray(DATA).toJavaList(EvidenceInfo.class);
        } else {
            log.info("证据库新对接根据案件id查询证据结果失败返回：{}", response);
            throw new BusinessException("证据中心查询证据失败：" + info.getString("message"));
        }
    }

    @Override
    public Integer getEvideceCountForCase(String caseId) {
        List<CaseDocumentCatalogChainInfoVo> caseDocumentCatalogChainInfosForApp = caseMainInfoService.getCaseDocumentCatalogChainInfosForApp(caseId);
        int count = 0;
        for (CaseDocumentCatalogChainInfoVo caseDocumentCatalogChainInfoVo : caseDocumentCatalogChainInfosForApp) {
            count += caseDocumentCatalogChainInfoVo.getCaseDocumentCatalogChainDetailVoList().size();
        }
        List<EvidenceInfo> caseEvidenceInfo = getCaseEvidenceInfo(caseId, false);
        count += caseEvidenceInfo.size();
        return count;
    }

    /**
     * 新增案源事件
     *
     * @param dto
     * @return
     */
    @Override
    public boolean reSaveCaseSourceEvent(CaseSourceEventSaveDto dto) {
        String territoryCode = dto.getTerritoryCode();
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(dto.getCaseSourceId());
        if (StringUtils.isBlank(territoryCode)) {
            if (null != caseSourceRegisterMainInfo) {
                territoryCode = caseSourceRegisterMainInfo.getLineCode().substring(0, 4);
            }
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        String url = exceptTzUrl;
        if (userDTO.getAreaCode().startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(territoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(territoryCode))) {
            url = apiurl;
        }
        System.out.println("案源事件url:----------------" + url);
        JSONObject param = new JSONObject();
        param.put("appKey", appKey);
        // 防止时间戳不一致
        String timestamp = getTimestamp();
        param.put("timestamp", timestamp);
        param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
        param.put("caseId", dto.getCaseSourceId());
        param.put("caseNo", dto.getCaseSourceId());
        param.put("caseName", dto.getCaseSourceName());
        param.put("casePart", "02");
        param.put("eventType", "98");
        // 执法人员信息
        setCaseSourceZfInfo(param, dto.getCaseSourceId());
        // 当事人信息
        setCaseSourcePartyInfo(dto.getCaseSourceId(), param);
        log.info(param.toJSONString());
        param.put("lawDeptCode", StringUtils.isNotBlank(caseSourceRegisterMainInfo.getHandleOrgCode()) ? caseSourceRegisterMainInfo.getHandleOrgCode().substring(13) : caseSourceRegisterMainInfo.getHandleOrgCode());
        param.put("lawDeptName", caseSourceRegisterMainInfo.getHandleOrgName());
        param.put("lawDeptOrgCode", caseSourceRegisterMainInfo.getHandleOrgCode());
        param.put("zfDeptCode", caseSourceRegisterMainInfo.getHandleDeptCode());
        param.put("zfDeptName", caseSourceRegisterMainInfo.getHandleDeptName());
        String response = HttpUtil.createPost(url.concat(saveCaseSourceEvent)).body(param.toJSONString()).execute().body();
        log.info("===============================================" + url.concat(saveCaseSourceEvent));
        JSONObject info = JSONObject.parseObject(response);
        if (TWO_HUNDRED.equals(info.getInteger(CODE))) {
            return true;
        } else {
            log.info("证据库新对接同步案件信息失败返回：{}", response);
        }
        return false;
    }

    @Override
    public List<Map> getCaseEvidenceInfoList(String caseId) {
        log.info("getEvidenceByCaseId 调用证据库证据接口 start");
        Result result = null;
        try {
            String caseTerritoryCode = "";
            String url = exceptTzUrl;
            String areaCode = "";
            CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            if (Objects.nonNull(mainInfo)){
                if (StringUtils.isNotEmpty(mainInfo.getLineCode())) {
                    caseTerritoryCode = mainInfo.getLineCode().substring(0,4);
                }
                areaCode = mainInfo.getCaseAreaCode();
            }
            if(ObjectUtil.isNotEmpty(areaCode) && areaCode.startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(caseTerritoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(caseTerritoryCode))) {
                url = apiurl;
            }
            JSONObject param = new JSONObject();
            String timestamp = getTimestamp();
            param.put("caseId", caseId);
            param.put("timestamp", timestamp);
            param.put("appKey", appKey);
            param.put("sign", DigestUtils.md5DigestAsHex((appKey.concat(appSecret).concat(timestamp)).getBytes(StandardCharsets.UTF_8)));
            log.info("getCaseEvidenceInfo -- 入参: {}", param);
            String response = HttpUtil.createPost(exceptTzUrl.concat("/cevidence/api/getCaseEvidenceInfo")).body(param.toJSONString()).execute().body();
            log.info("getCaseEvidenceInfo -- 出参: {}", response);
            result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())){
                Object data=  result.getData();
                List<Map> arrayLists = JSON.parseArray(JSON.toJSONString(data), Map.class);
                return arrayLists;
            }
        } catch (Exception e) {
            log.error("getEvidenceByCaseId 调用证据库证据接口报错", e);
            e.printStackTrace();
        }
        return null;
    }
}
